<template>
  <el-form :model="item" ref="moForm" :rules="rules" label-width="130px">
    <el-form-item prop="schoolId" label="所属院校" v-if="add && add === '添加'">
      <el-select v-model="item.schoolId" placeholder="请选择所属院校" @change="topic_data">
        <el-option
          v-for="it in schoolList"
          :key="it.id"
          :label="it.name"
          :value="it.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="type" label="发帖方式">
      <el-radio v-model="item.type" label="1" border :disabled="item.type=='2'">官方发帖</el-radio>
      <el-radio v-model="item.type" label="3" border :disabled="item.type=='2'">虚拟发帖</el-radio>
      <el-radio v-model="item.type" label="2" border v-if="edit&&edit=='修改'">真实发帖</el-radio>
    </el-form-item>
    <el-form-item prop="userId" label="虚拟学生" v-if="item.type == '3'">
      <el-select v-model="item.userId" filterable placeholder="请选择虚拟学生">
        <el-option
          v-if="item.userId=='1'"
          label="官方发帖"
          :value="item.userId"
        ></el-option>
        <el-option
          v-for="it in dummyStudentList"
          :key="it.id"
          :label="it.nickname"
          :value="it.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="cateId" label="话题" v-if="item.schoolId">
      <el-select
        v-model="item.cateId"
        filterable
        placeholder="请选择话题"
        @change="findTopic"
      >
        <el-option label="校园官方（官方发帖时选择）" value="0">

        </el-option>
        <el-option
          v-for="it in topicList"
         
          :key="it.id"
          :label="it.name"
          :value="it.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="title" label="标题">
      <el-input v-model.trim="item.title" placeholder="请输入标题"></el-input>
    </el-form-item>
    <el-form-item prop="body" label="内容">
      <el-input
        type="textarea"
        :autosize="{ minRows: 6, maxRows: 12 }"
        placeholder="请输入内容"
        v-model.trim="item.body"
      ></el-input>
    </el-form-item>
    <el-form-item prop="images" label="图片">
      <el-upload
        class="upload-demo"
        action="https://wechat.zhengjkj.com/xyxy/wxapp/public/upload_asset"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="successImg"
        :file-list="fileList"
        list-type="picture"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
    </el-form-item>
    <el-form-item prop="mobile" label="联系方式">
      <el-input
        v-model.trim="item.mobile"
        placeholder="请输入联系方式"
      ></el-input>
    </el-form-item>
    <el-form-item prop="views" label="浏览量">
      <el-input v-model.trim="item.views" placeholder="请输入浏览量"></el-input>
    </el-form-item>
    <el-form-item prop="callMe" label="是否留下联系方式" v-if="edit&&edit=='修改'">
      <el-radio v-model="item.callMe" :label="0" border>不留下</el-radio>
      <el-radio v-model="item.callMe" :label="1" border>留下</el-radio>
    </el-form-item>
    <el-form-item prop="anonymity" label="是否匿名"  v-if="edit&&edit=='修改'">
      <el-radio v-model="item.anonymity" :label="0" border>实名</el-radio>
      <el-radio v-model="item.anonymity" :label="1" border>匿名</el-radio>
    </el-form-item>
    <el-form-item prop="deleted" label="状态">
      <el-radio v-model="item.deleted" label="0" border>展示</el-radio>
      <el-radio v-model="item.deleted" label="1" border>隐藏</el-radio>
    </el-form-item>
    <el-form-item prop="isTop" label="是否置顶">
      <el-radio v-model="item.isTop" label="0" border>不置顶</el-radio>
      <el-radio v-model="item.isTop" label="1" border>置顶</el-radio>
    </el-form-item>
    <el-form-item prop="isHot" label="是否热帖">
      <el-radio v-model="item.isHot" label="0" border>非热帖</el-radio>
      <el-radio v-model="item.isHot" label="1" border>热帖</el-radio>
    </el-form-item>

    <el-form-item prop="topTime" label="置顶到期时间">
      <el-date-picker
        v-model="item.topTime"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期"
      >
      </el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSubmitClick()">提交</el-button>
      <el-button @click="handleBackClick">返回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {filterSchool} from '../../../utils/common';
import { getSchoolList, topicList, dummyStudentList } from "./api";
export default {
  props: ["item", "add","edit"],
  data() {
    return {
      topic: {},
      schoolList: [],
      schoolId: "",
      topicList: [],
      topicId: "",
      dummyStudentList: [],
      dummyStudentId: "",
      fileList: [],
      reader: null,
      imgBase: "",
      iconImage: "",
      images: "",
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        views: [{ required: true, message: "请输入浏览量", trigger: "blur" }],
        body: [{ required: true, message: "请输入内容", trigger: "blur" }],
        // mobile: [
        //   { required: true, message: "请输入联系方式", trigger: "blur" },
        // ],
        deleted: [
          { required: true, message: "请输选择状态", trigger: "change" },
        ],
        isTop: [
          { required: true, message: "请输选择是否置顶", trigger: "change" },
        ],
        isHot: [
          { required: true, message: "请输选择是否为热帖", trigger: "change" },
        ],
        cateId:[ { required: true, message: "请输选择话题", trigger: "change" },]
        // topTime: [
        //   {
        //     required: true,
        //     message: "请输选择置顶到期时间",
        //     trigger: "change",
        //   },
        // ],
        // images: [{ required: true, message: "请选择图片", trigger: "blur" }],
      },
    };
  },
  computed: {
    obj() {
      // this.item.type == "0"是官方发帖，“1”是虚拟学生发帖
      return {
        userId: this.item.type == "1" ? "1" : this.item.userId,
        cate: this.item.type == "1" ? "校园官方" : this.topic.name,
        title: this.item.title,
        body: this.item.body,
        mobile: this.item.mobile,
        views: this.item.views,
        isTop: this.item.isTop,
        isHot: this.item.isHot,
        deleted: this.item.deleted,
        topTime: this.item.topTime,
        images: this.images,
        schoolId: this.item.schoolId,
        type: this.item.type,
        cateId: this.item.type == "1" ? "0" : this.item.cateId,
        callMe:this.item.callMe,
        anonymity:this.item.anonymity,
      };
    },
  },
  watch: {},
  created() {
    this.refresh_data();
    this.selectChange();
    // this.topic_data();
    this.reader = new FileReader();
    this.reader.onload = (e) => {
      this.imgBase = e.target.result;
    };
    setTimeout(() => {
      if (this.item.images) {
        this.images = this.item.images;
        this.item.images.split(",").forEach((i) => {
          this.fileList = [...this.fileList, { name: i, url: i }];
        });
        console.log(this.fileList, "sss=====");
        // this.iconImage = this.item.image;
      }
      if(this.item.schoolId){
        // this.schoolId=this.item.schoolId;
        this.topic_data();
      }
    }, 500);
    this.refresh_data();
  },
  methods: {
    findTopic(value) {
      this.topic = this.topicList.find((i) => i.id === value);
      console.log(this.topic, "topic");
    },

    // 查询虚拟学生
    async selectChange() {
      this.loadList = true;
      const res = await dummyStudentList();
      if (res.code === 1) {
        this.dummyStudentList = res.data;
      }
      this.loadList = false;
    },

    // 话题列表
    topic_data() {
      topicList(this.item.schoolId)
        .then((data) => {
          if (data.code === 1) {
           
            this.topicList = data.data;
          } else {
            this.$message.error(data.msg);
          }
          this.loadList = false;
        })
        .catch((err) => {
          console.log(err);
          this.loadList = false;
        });
    },

    // 获取院校列表
    refresh_data() {
      getSchoolList()
        .then((data) => {
          console.log(data, "=====");
          if (data.code === 1) {
            this.schoolList = filterSchool(data.data);
          } else {
            this.$message.error(data.description);
          }
          this.loadList = false;
        })
        .catch((err) => {
          console.log(err);
          this.loadList = false;
        });
    },
    successImg(response, file, fileList) {
      this.images = "";
      fileList.forEach((i) => {
        this.images += i.response.data + ",";
      });
      this.images = this.images.substring(0, this.images.length - 1);
      console.log(this.images, "tupian");
      console.log(this.fileList, "tupian");
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleBackClick() {
      this.$router.go(-1);
    },
    handleSubmitClick() {
      this.$emit("doSubmit");
    },
    valid(callback) {
      this.$refs["moForm"].validate((valid) => {
        callback(valid);
      });
    },
    setImg() {
      const target = document.getElementById("fileInput");
      target && target.click();
    },
    imgChange(e) {
      console.log(e);
      const img = e.target.files[0];
      if (img.size / 1024 < 2 * 1024) {
        this.reader.readAsDataURL(img);
        this.item.imageFile = img;
        setTimeout(() => {
          const pos = this.imgBase.indexOf("base64") + 7;
          this.imgBase = this.imgBase.substr(pos);
          this.iconImage = "data:image/png;base64," + this.imgBase;
        }, 500);
      } else {
        this.$message.error("图片大小不可超过2M");
      }
      this.$refs["moForm"].validateField("imageFile");
    },
  },
};
</script>

<style scoped>
#fileInput {
  width: 0;
  height: 0;
  overflow: hidden;
}

.setimg {
  float: left;
  margin-left: 0;
}

.imgbox {
  border: 1px solid #eee;
  width: 200px;
  height: auto;
}

.imgbox img {
  align: center;
  max-width: 100%;
}

.imginfo {
  font-size: 12px;
  color: #666;
}
</style>
